<?php
namespace app\admin\controller;

use app\admin\model\PublicwelfareModel;
use think\Db;
use think\Validate;

class Publicwelfare extends User
{
    public function index()
    {
        $startTime = '';
        $endTime = '';
        extract(input());
        $where = [];
        if (isset($keyword) && !empty($keyword)) {
            $where['keyword'] = ['like', '%'.$keyword.'%'];
        }
        if (isset($title) && !empty($title)) {
            $where['title'] = ['like', '%'.$title.'%'];
        }
        if (isset($start_time) && !empty($start_time)) {
            $where['create_time'] = ['>=', strtotime($start_time)];
            $startTime = $start_time;
        }
        if (isset($end_time) && !empty($end_time)) {
            $where['create_time'] = ['<=', strtotime($end_time)];
            $endTime = $end_time;
        }
        $data = PublicwelfareModel::where($where)
            ->order('create_time DESC')
            ->paginate(5);
        $page = $data->render();

        return $this->fetch('index', [
            'data' => $data,
            'page' => $page,
            'start_time' => $startTime,
            'end_time' => $endTime
        ]);
    }
    public function add()
    {
        if ($this->request->isPost()) {
            $data = input();
            $rule = [
                'title' => 'require',
                'desc' => 'require',
                'keyword' => 'require',
                'from' => 'require',
                'author' => 'require',
                'content' => 'require'
            ];
            $msg = [
                'title.require' => '请输入文章标题',
                'title.desc' => '请输入文章描述',
                'title.keyword' => '请输入文章描述',
                'title.from' => '请输入文章来源',
                'title.author' => '请输入文章作者',
                'title.content' => '请输入文章内容'
            ];
            $validate = Validate::make($rule, $msg);
            $result = $validate->check($data);
            if (true !== $result) {
                return $this->error($validate->getError());
            }
            $data['create_time'] = time();
            $add = PublicwelfareModel::create($data);
            if ($add) {
                return $this->success('添加成功', 'admin/publicwelfare/index');
            } else {
                return $this->error('添加失败');
            }
        }
        return $this->fetch();
    }
}